package fr.phil.daoimphql;

import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.Logger;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import fr.phil.daoservice.Iservices;
import fr.phil.model.beans.Article;
import fr.phil.model.beans.Pays;

/**
 * PhilippeBlog .
 * @author Philippe
 * Package : fr.phil.daoimphql
 * Fichier : ImpHqlPays.java.java
 * Date : 24 janv. 2013 
 */
public class ImpHqlArticle  extends HibernateDaoSupport 
	implements Iservices<Article> {

	// -------------------------------------------------------------
	// Attributs
	// -------------------------------------------------------------

	/**
	 * Le logguer log4j.
	 */
	private static final Logger LOG = Logger.getLogger(ImpHqlArticle.class);

	/**
	 * initialisation du bean article.
	 */
	private Article article = null;

	/**
	 * liste des objets Article.
	 */
	private List<Article> listeArticle = new ArrayList<Article>();
	
	/**
	 * La session courante d'hibernate.
	 */
	private Session hibSession;
	
	
	/**
	 * La transaction courante d'hibernate.
	 */
	Transaction hibTransaction;
	
	/**
	 * Erreur de l'operation.
	 */
	private int error = 0;
	
	@Override
	public final int saveObject(final Article object) {
		LOG.trace("Entering in saveObject " + object.getClass());
		try {
			hibSession = getSessionFactory().getCurrentSession();
			hibTransaction = hibSession.beginTransaction();
			hibSession.save(object);
			hibTransaction.commit();
		} catch (HibernateException e) {
			hibTransaction.rollback();
			error = 1;  
			LOG.error(e);
		}
		LOG.trace("Exit saveObject " + object.getClass() + " : error " + error);
		return error;
		// ou remplacer le tout par un gethibernateTemplate() ...)
	}

	@Override
	public int deleteObject(final Article object) {
		LOG.trace("Entering in deleteObject " + object.getClass());
		try {
			hibSession = getSessionFactory().getCurrentSession();
			hibTransaction = hibSession.beginTransaction();
			hibSession.delete(object);

			hibTransaction.commit();

		} catch (HibernateException e) {
			hibTransaction.rollback();
			error = 1;			
			LOG.error(e);
		}
		LOG.trace("Exist deleteObject " + object.getClass() 
				+ " : error " + error);
		return error;
	}

	@Override
	public int updateObject(final Article object) {
		return error;
	}

	@Override
	public Article getObject(final int idObjet) {
		return article;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Article> listObject() {
		LOG.trace("Entering in listObject");
		try {
			listeArticle = getHibernateTemplate().find("from Article");
		} catch (HibernateException e) {
			error = 1;			
			LOG.error(e);
		}
		LOG.trace("Exist listObject Article : error " + error);
		return listeArticle;
	}

}
